const gulp = require("gulp");
const connect = require("gulp-connect");
const sass = require("gulp-sass")(require("sass"));
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");
const babel = require("gulp-babel");
const fs = require("fs");
const sourcemaps = require("gulp-sourcemaps");

gulp.task("copyHtml", (done) => {
  gulp
    .src(["src/html/**/*.html", "!src/index.html"])
    .pipe(gulp.dest("dist/html"))
    .pipe(connect.reload());
  done();
});

gulp.task("copyIndex", (done) => {
  gulp.src(["src/index.html"]).pipe(gulp.dest("dist/")).pipe(connect.reload());
  done();
});

gulp.task("copyCss", (done) => {
  gulp
    .src(["src/css/**/*.css"])
    .pipe(gulp.dest("dist/css"))
    .pipe(connect.reload());
  done();
});

gulp.task("copyImg", (done) => {
  gulp.src(["src/img/**"]).pipe(gulp.dest("dist/img")).pipe(connect.reload());
  done();
});

gulp.task("copyJs", (done) => {
  gulp
    .src(["src/js/**/*.js"])
    .pipe(gulp.dest("dist/js"))
    // .pipe(
    //   babel({
    //     presets: ["@babel/preset-env"],
    //   })
    // )
    // .pipe(
    //   rename({
    //     suffix: ".es5",
    //   })
    // )
    // .pipe(gulp.dest("dist/js"))
    // .pipe(uglify())
    // .pipe(
    //   rename({
    //     suffix: ".min", //后缀
    //   })
    // )
    // .pipe(gulp.dest("dist/js"))
    .pipe(connect.reload());
  done();
});

gulp.task("import", (done) => {
  fs.readFile("package.json", (err, con) => {
    if (err) return err;
    const dep = JSON.parse(con.toString()).dependencies;

    for (let i in dep) {
      gulp.src(`node_modules/${i}/dist/${i}.js`).pipe(gulp.dest("dist/lib"));
      gulp
        .src(`node_modules/${i}/dist/${i}.min.js`)
        .pipe(gulp.dest("dist/lib"));
    }
  });
  done();
});

function sassError(error) {
  console.error(error.toString());
  this.emit("end");
}

gulp.task("sass", (done) => {
  gulp
    .src("src/sass/**/*.scss")
    .pipe(sourcemaps.init())
    .pipe(sass())
    .on("error", sassError)
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest("dist/css"))
    .pipe(connect.reload());

  done();
});

//监听文件变化，一旦指定文件发生改变，会触发对应任务执行
gulp.task("watch", (done) => {
  gulp.watch(
    ["src/html/**/*.html", "!src/index.html"],
    gulp.series("copyHtml")
  );
  gulp.watch("src/index.html", gulp.series("copyIndex"));
  gulp.watch("src/css/**/*.css", gulp.series("copyCss"));
  gulp.watch("src/js/**/*.js", gulp.series("copyJs"));
  gulp.watch("src/sass/**/*.scss", gulp.series("sass"));
  gulp.watch("src/img/**", gulp.series("copyImg"));
  done();
});
//服务器 服务器对应的根目录 dist
gulp.task("server", (done) => {
  connect.server({
    root: "dist",
    livereload: true,
  });
  done();
});

gulp.task(
  "build",
  gulp.parallel("copyHtml", "copyImg", "copyIndex", "copyCss", "copyJs", "sass")
);

gulp.task("default", gulp.series("build", "server", "watch"));
